<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="700px"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        style="width: 95%"
      >
        <el-form-item label="看板编号" prop="databoradCode">
          <el-input
            v-if="!props.isReadonly"
            v-model="formData.databoradCode"
            placeholder="请输入看板编号"
            clearable
          />
          <span v-else>{{ formData.databoradCode }}</span>
        </el-form-item>
        <el-form-item label="看板名称" prop="databoradName">
          <el-input
            v-if="!props.isReadonly"
            v-model="formData.databoradName"
            placeholder="请输入看板名称"
            clearable
          />
          <span v-else>{{ formData.databoradName }}</span>
        </el-form-item>
        <el-form-item label="目录" prop="catalogId">
          <SelectOriganization
            @change="getSelectIds"
            :selectData="formData.catalogId"
            :isMultiple="false"
            :data="catalogData"
            :disabled="props.isReadonly"
          />
        </el-form-item>
        <el-form-item label="看板类型" prop="databoradType">
          <el-radio-group v-model="formData.databoradType">
            <el-radio
              v-for="(item, index) in typeList"
              :key="index"
              :label="item.value"
              :disabled="props.isReadonly"
              border
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="看板地址" prop="databoradUrl">
          <el-input
            v-if="!props.isReadonly && formData.databoradType === '1'"
            placeholder="pages/system/user/index"
            v-model="formData.databoradUrl"
          >
            <template #prepend>views/</template>
            <template #append>.vue</template>
          </el-input>

          <el-input
            v-if="!props.isReadonly && formData.databoradType === '2'"
            v-model="formData.databoradUrl"
            placeholder="请输入报表地址"
            clearable
          />
          <span v-if="props.isReadonly">{{ formData.databoradUrl }}</span>
        </el-form-item>
        <el-form-item label="看板参数" prop="databoradParam">
          <el-input
            v-if="!props.isReadonly"
            v-model="formData.databoradParam"
            placeholder='请输入看板参数, JSON格式例如：{ "id": 1, "type": 2 }'
            clearable
          />
          <span v-else>{{ formData.databoradParam || "无" }}</span>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-radio-group v-model="formData.enabled">
            <el-radio
              v-for="(item, index) in enabledList"
              :key="index"
              :label="item.value"
              :disabled="props.isReadonly"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-if="!props.isReadonly"
            v-model="formData.remarks"
            placeholder="请输入备注"
            type="textarea"
            show-word-limit
            :maxlength="250"
            :autosize="{ minRows: 3, maxRows: 4 }"
            clearable
          />
          <span v-else>{{ formData.remarks || "无" }}</span>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="SYSDATABORADINFOADDORUPDATE">
import request from "@/utils/request";
import { useDictionary } from "@/utils/useTable";

const emit = defineEmits(["reset-table", "change-visible"]);

const catalogData = {
  name: "目录",
  defaultProps: {
    children: "nodes",
    label: "catalogName",
    value: "id",
  },
  api: "/system/databoardCatalog/getTree",
};

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

function getSelectIds(ids) {
  formData.catalogId = ids;
}

// 获取字典表数据
const typeList = useDictionary("DataBoardType");
const enabledList = useDictionary("Enabled");

const rules = reactive({
  databoradCode: [
    { required: true, message: "请输入看板编号", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  databoradName: [
    { required: true, message: "请输入看板名称", trigger: "blur" },
    {
      required: true,
      min: 1,
      max: 50,
      message: "长度在 1 到 50 个字符",
      trigger: "blur",
    },
  ],
  catalogId: [
    {
      required: true,
      message: "请选择目录",
      trigger: "blur",
    },
  ],
  databoradType: [
    {
      required: true,
      min: 1,
      max: 10,
      message: "长度在 1 到 10 个字符",
      trigger: "blur",
    },
  ],
  databoradUrl: [
    { required: true, message: "请输入看板地址", trigger: "blur" },
    {
      required: true,
      min: 1,
      max: 250,
      message: "长度在 1 到 250 个字符",
      trigger: "blur",
    },
  ],
  databoradParam: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  version: "",
  databoradCode: "",
  databoradName: "",
  catalogId: "",
  databoradType: "1",
  databoradUrl: "",
  databoradParam: "",
  enabled: "1",
  remarks: "",
  deleted: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        version,
        databoradCode,
        databoradName,
        catalogId,
        databoradType,
        databoradUrl,
        databoradParam,
        enabled,
        remarks,
        deleted,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
      } = newVal;
      Object.assign(formData, {
        id,
        version,
        databoradCode,
        databoradName,
        catalogId,
        databoradType,
        databoradUrl,
        databoradParam,
        enabled: enabled.toString(),
        remarks,
        deleted,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
      });
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.version = "";
  formData.databoradCode = "";
  formData.databoradName = "";
  formData.catalogId = "";
  (formData.databoradType = "1"), (formData.databoradUrl = "");
  formData.databoradParam = "";
  formData.enabled = "1";
  formData.remarks = "";
  formData.deleted = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
}

const loading = ref(false);

/** 数据看板保存提交 */
function handleSubmit() {
  // 看板参数json格式判断
  try {
    const params = formData.databoradParam
      ? JSON.parse(formData.databoradParam)
      : "";
    if (
      formData.databoradParam &&
      Object.prototype.toString.call(params).slice(8, -1) !== "Object"
    ) {
      ElMessage.error("看板参数json格式不正确, 请按照示例填写");
      return;
    }
  } catch (error) {
    ElMessage.error("看板参数json格式不正确, 请按照示例填写");
    return;
  }
  // 开始校验
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/system/databoradinfo/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>

<style lang="scss" scoped>
:deep(.el-radio.is-bordered) {
  background-color: var(--el-color-info-light-9);
  border: none !important;
  color: var(--el-color-info);
  font-weight: 700;
  margin-right: 15px;
  .el-radio__inner {
    display: none;
  }
}
:deep(.el-radio.is-bordered.is-checked) {
  background-color: var(--el-color-primary-light-8) !important;
  color: var(--el-color-primary) !important;
  border: none !important;
  font-weight: 700 !important;
  .el-radio__input.is-checked .el-radio__inner {
    display: none;
  }
}
</style>
